import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';

import '../Home/views/DL_generator_homePage.dart';
import '../tools/DL_Segment.dart';
import '../tools/DL_generator.dart';
import '../tools/FL_CustomLoading.dart';
import '../tools/sqLite/EJ_myTicketEntity.dart';
import 'DL_GeneraAnalyticsView.dart';

class DlGeneratorpagevc extends StatefulWidget {
  const DlGeneratorpagevc({super.key});

  @override
  State<DlGeneratorpagevc> createState() => _DlGeneratorpagevcState();
}

class _DlGeneratorpagevcState extends State<DlGeneratorpagevc>
    with AutomaticKeepAliveClientMixin {
  ///保存选号到数据库
  MyTicketEntity ticketEntity = MyTicketEntity.instan();
  var _chooseNumbers = []; //要保存的号码详细信息
  int _scoredForNumbers = 0;

  var _numbers = []; //生成的号码-->int
  late List<String> _saveNumbers = []; //生成的号码-->string

  int _typeIndex = 0; //pm index

  ///
  _getGeneratorNumber() async {
    _scoredForNumbers = await DL_Generator.instance.scoredForNumbers;

    ///
    String finalNumber = await DL_Generator.instance.finalNumber;

    ///
    List<String> charArray = finalNumber.split('');
    _saveNumbers = charArray;

    // setState(() {});
  }

  ///save to checker
  _EJ_saveTpChecker() async {
    await _getGeneratorNumber();
    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading();
    });

    if (_saveNumbers.isEmpty) {
      BotToast.closeAllLoading();
      return;
    }
    // 获取当前时间戳（毫秒）
    int currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
    var tickets = {
      "name": "Lucky Number",
      "time": currentTimeMillis,
      "numbers": jsonEncode(_saveNumbers),
    };

    ///保存选号
    // int save = await ticketEntity.insert(tickets);
    await ticketEntity.insert(tickets);
    Future.delayed(const Duration(milliseconds: 300), () {
      BotToast.closeAllLoading();
      BotToast.showText(text: 'Save successfully!');
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _getGeneratorNumber();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Image.asset(
          'assets/sys_imgs/DearLottery Logo.png',
          width: 160,
          height: 50,
        ),
        backgroundColor: DL_Config.DL_navgatBarColor,
        foregroundColor: DL_Config.DL_navgatBarTitleColor,
        centerTitle: true,
      ),
      body: Container(
        color: DL_Config.DL_pageBgColor,
        child: Column(
          children: [
            segmentView(),
            generatorView(),
            contentListView(),
            bottomView(),
          ],
        ),
      ),
    );
  }

  Widget segmentView() {
    return Container(
      width: double.infinity,
      height: 40,
      color: Colors.white,
      child: SizedBox(
        height: 40,
        child: Padding(
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: DlSegment(
            segments: {
              '1pm': '1PM',
              '6pm': '6PM',
              '8pm': '8PM',
            },
            sliderColor: HexColor('#ff3433'),
            onSegmentChange: (index, value) => {
              debugPrint('value---$value,index---$index'),
              // _onTabChanged(index),
              setState(() {
                _typeIndex = index;
              })
            },
          ),
        ),
      ),
    );
  }

  Widget generatorView() {
    return DL_generator_home(
      typeIndex: _typeIndex,
      generateSuccess: (score) {
        _scoredForNumbers = DL_Generator.instance.scoredForNumbers;
        // print('_scoredForNumbers-->$_scoredForNumbers,score-->$score');
        // _getGeneratorNumber();
        setState(() {});
      },
    );
  }

  Widget contentListView() {
    return Expanded(
        child: ListView(
      padding: const EdgeInsets.all(15),
      children: [
        DlGeneraanalyticsview(
          dataType: ViewType.type_RegularNumbersFrequency,
        ),
        DlGeneraanalyticsview(
          dataType: ViewType.type_SkippedNumbersAnalytics,
        ),
        DlGeneraanalyticsview(
          dataType: ViewType.type_ConsecutiveNumbersAnalytics,
        ),
        DlGeneraanalyticsview(
          dataType: ViewType.type_SumsofNumbers,
        ),
        DlGeneraanalyticsview(
          dataType: ViewType.type_EvenOddofNumbers,
        ),
      ],
    ));
    // return Container();
  }

  Widget bottomView() {
    String text = 'Score of the Numbers: $_scoredForNumbers';
    return Container(
      height: 45,
      color: Colors.white,
      child: Row(
        children: [
          const SizedBox(width: 15),
          Text(
            text,
            style: const TextStyle(
              fontSize: 10,
              fontWeight: FontWeight.w400,
            ),
          ),
          const Spacer(),
          OutlinedButton(
            onPressed: () {
              debugPrint('Save to Checker');
              _EJ_saveTpChecker();
            },
            style: ButtonStyle(
                backgroundColor: WidgetStatePropertyAll(DL_Config.DL_MainColor),
                foregroundColor: WidgetStateProperty.all(Colors.white),
                side: WidgetStateProperty.all(
                    //边框
                    BorderSide(
                  color: DL_Config.DL_MainColor, //颜色
                  width: 1.0, //宽度
                )),
                minimumSize: const MaterialStatePropertyAll(Size(40, 35))),
            child: const Text(
              "Save to Checker",
              style: TextStyle(fontWeight: FontWeight.w400, fontSize: 13),
            ),
          ),
          const SizedBox(
            width: 15,
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
